import { defineComponent } from "vue";

import { FieldPropsDefine } from "../types";
// import SchemaItem from "../SchemaItem";
// console.log(SchemaItem);
import { useVJSFContext } from "../context";

import { isObject } from "../utils";

export default defineComponent({
  name: "ObjectField",
  props: FieldPropsDefine,
  setup(props) {
    const context = useVJSFContext();

    const handleObjectFiledChange = (key: string, v: any) => {
      const value: any = isObject(props.value) ? props.value : {};

      if (v === undefined) {
        delete value[key];
      } else {
        value[key] = v;
      }

      props.onChange(value);
    };
    return () => {
      const { schema, rootSchema, value, errorSchema, uiSchema } = props;
      const { SchemaItem } = context;
      const properties = schema.properties || {};
      const currentValue: any = isObject(value) ? value : {};

      return Object.keys(properties).map((k: string, index: number) => (
        <SchemaItem
          errorSchema={errorSchema[k] || {}}
          schema={properties[k]}
          rootSchema={rootSchema}
          value={currentValue[k]}
          uiSchema={uiSchema.properties ? uiSchema.properties[k] || {} : {}}
          key={index}
          onChange={(v: any) => handleObjectFiledChange(k, v)}
        ></SchemaItem>
      ));
    };
  },
});
